<?php
/**
 * Created by PhpStorm.
 * userValidate: hms
 * Date: 2018/8/7
 * Time: 9:27
 */

namespace app\firm\controller;

use think\Controller;
use think\Config;
use redis\Redis;
use think\Request;
use think\Db;
use app\firm\model\MoneyCom;
use app\firm\model\ProjectBank;
use app\firm\model\ProjectUser;
use app\firm\model\Notice;
use expand\Yunst;
use expand\YunPay;

class Money extends Common
{
    
    /*
     * 提现/充值列表
     * @param Request $request
     * @param MoneyCom $money
     * @author cpy(1442435897@qq.com)
     * @return \think\response\Json
     */
    public function getCashList(Request $request , MoneyCom $moneyCom) {
        $user_info = $request->firm_info;
        $param = $request->param();
        $pageNumber = $param['pageNumber'] ? $param['pageNumber'] : 1;
        $pageSize = $param['pageSize'] ? $param['pageSize'] : 10;
        $limit = ($pageNumber - 1) * $pageSize . ',' . $pageSize;
        $where['company_id'] = ['eq',$user_info['id']];
        $where['type'] = ['eq',$param['type']];
        $res = $moneyCom->selectProjectInfo($where,$limit);
        foreach ($res as $k => $val) {
            $prefix = substr($val['bank_num'],0,4);
            $suffix = substr($val['bank_num'],-4,4);
            $maskBankCardNo = $prefix." **** **** **** ".$suffix;
            $res[$k]['bank_num'] = $maskBankCardNo;
        }
        $total = $moneyCom->selectInfo($where,'id');
        $result = Config::get('code.success');
        $result['data'] = $res;
        $result['total'] = count($total);
        return json($result);
    }
    
    /*
     * 获取余额
     * @param Request $request
     * @author cpy(1442435897@qq.com)
     * @return \think\response\Json
     */
    public function getMoney(Request $request) {
        $user_info = $request->firm_info;
        $result = Config::get('code.success');
        $result['money'] = $user_info['money'];
        return json($result);
    }
    
    /*
     * 提现
     * @param Request $request
     * @param MoneyCom $moneyCom
     * @param ProjectBank $projectBank
     * @param ProjectUser $projectUser
     * @author cpy(1442435897@qq.com)
     * @return \think\response\Json
     */
    public function getCash(Request $request , MoneyCom $moneyCom , ProjectBank $projectBank , ProjectUser $projectUser , Notice $notice) {
        $user_info = $request->firm_info;
        $param = $request->param();
        $redis = Redis::instance();
        $code = $redis->get('pay_code_' . $user_info['mobile']);
        $where['pjtuser_id'] = ['eq',$user_info['id']];
        $where['id'] = ['eq',$param['bank_id']];
        $bank = $projectBank->getBankInfo($where);
        if($param['money'] < 0){
            return json(Config::get('code.errorMoney'));
        }
        if($code != $param['code']){
            return json(Config::get('code.codeFail'));
        }
        if(empty($bank)){
            return json(Config::get('code.emptyBank'));
        }
        if (empty($user_info['pay_password'])) {
            return json(Config::get('code.emptyPayPwd'));
        }
        if ($user_info['pay_password'] != sha1(md5($param['pay_password'] . $user_info['pay_salt']))) {
            return json(Config::get('code.errorPayPwd'));
        }
//        if ($param['money'] < Config::get('queue.lowestCash')) {
//            $result['status'] = 301;
//            $result['msg'] = '提现金额最低不得少于'.Config::get('queue.lowestCash').'元!';
//            return json($result);
//        }
        if ($user_info['money'] < $param['money']) {
            return json(Config::get('code.overBalance'));
        }
        Db::startTrans();
        try {
            $data = [
                'order_num' => createOrderNo('TX'),
                'company_id' => $user_info['id'],
                'mobile' => $user_info['mobile'],
                'money' => $param['money'],
                'fee' => Config::get('queue.fee'),
                'true_money' => $param['money'] - Config::get('queue.fee'),
                'bank_name' => $bank['bank_name'],
                'bank_num' => $bank['bank_num'],
                'type' => 2,
            ];
            $moneyCom->save($data);
            $setMoney = $user_info['money'] - $param['money'];
            $projectUser->where('id',$user_info['id'])->update(['money'=>$setMoney]);
            $datas = [
                'uid' => $user_info['id'],
                'title' => '提现',
                'content' => '您好,企业家,您于'.date('Y-m-d H:i:s').'发起提现,共计'.$param['money'].'元,提现金额将于3-7个工作日到您的银行账户,请您注意查收.如有疑问,欢迎致电400-605-9006',
                'type' => 2
            ];
            $notice->save($datas);
            $token = $redis->get('user:' . $user_info['id']);
            $user_info['money'] = $setMoney;
            $redis->hSet('firm_info' , $token , json_encode($user_info));
            Db::commit();
            $result = Config::get('code.success');
        } catch (\Exception $e) {
            Db::rollback();
            return $e->getMessage();
        }
        return json($result);
    }
    
    /*
     * 充值
     * @param Request $request
     * @param MoneyCom $moneyCom
     * @param Yunst $YunClass
     * @author cpy(1442435897@qq.com)
     * @return \think\response\Json
     */
    public function recharge(Request $request, MoneyCom $moneyCom, Yunst $YunClass, YunPay $payClass) {
        $user_info = $request->firm_info;
        $param = $request->param();
//        if ($param['money'] < Config::get('queue.lowestCash')) {
//            $result['status'] = 301;
//            $result['msg'] = '充值金额最低不得少于'.Config::get('queue.lowestCash').'元!';
//            return json($result);
//        }
        if(empty($param['bank_code'])){
            return json(Config::get('code.enptyBankCode'));
        }
        $reFee = Config::get('queue.reFee');
        $fee = $param['money'] < 200 ? 1 : round($reFee / 100 * $param['money'], 2);
        $order = [
            'company_id' => $user_info['id'],
            'mobile' => $user_info['mobile'],
            'money' => $param['money'],
            'true_money' => sprintf("%.2f",$param['money'] + $fee),
            'fee' => $fee,
            'order_num' => createOrderNo('NO'),
            'type' => 1,
            'bank_code' => $param['bank_code']
        ];
        $res = $moneyCom->allowField(true)->save($order);
        if (!$res) {
            return json(Config::get('code.error'));
        }
        $message = $YunClass->createRech3($user_info['bizUserId'], $order);
        if ($message['status'] != 'OK') {
            $result['status'] = 301;
            $result['msg'] = $message['message'];
            return json($result);
        }
        $signedValue = json_decode($message['signedValue'], true);
        $moneyCom->save(['order_no' => $signedValue['orderNo']],['order_num' => $signedValue['bizOrderNo']]);
        $payClass = new YunPay();
        $url = $payClass->surePay($user_info['bizUserId'], $signedValue['bizOrderNo']);
        $result = Config::get('code.success');
        $result['url'] = $url;
        return json($result);
    }
    
    public function test(Request $request) {
        $row = '{s:5:"sysid";s:12:"100009000406";s:3:"rps";s:540:"{&quot;status&quot;:&quot;OK&quot;,&quot;returnValue&quot;:{&quot;buyerBizUserId&quot;:&quot;hryqy17602867077&quot;,&quot;amount&quot;:100,&quot;bizOrderNo&quot;:&quot;NO1558941025779565889&quot;,&quot;payDatetime&quot;:&quot;2019-05-27 15:12:49&quot;,&quot;orderNo&quot;:&quot;1132907154773135360&quot;,&quot;payInterfacetrxcode&quot;:&quot;Allinpay&quot;,&quot;payInterfaceOutTradeNo&quot;:&quot;111938900000670881&quot;,&quot;extendInfo&quot;:&quot;&quot;},&quot;service&quot;:&quot;OrderService&quot;,&quot;method&quot;:&quot;pay&quot;}";s:9:"timestamp";s:19:"2019-05-27 15:12:49";s:1:"v";s:3:"1.0";s:4:"sign";s:172:"BmwrbzW0ECuRvJ8V1YflPen7oREnU5mXBfzipz9gw4vRfh8BtKDFJ4ItpEdyyMAP8VMOwbVoiWOpRbWsdT0sQNdClu1XfmrUL5sns54dWWaFuYOjVVaELyZ1Gg7yQNlhWozJY7hqkpwXjxJLiSWXs7gWvFVWPskGP/g75u76gWI=";}';
        $res = unserialize($row);
        //$res = htmlspecialchars_encode($row,true);
        halt($res);
    }

}